package com.bill99.util;

import org.apache.commons.httpclient.HttpStatus;

import javax.activation.DataHandler;
import javax.activation.DataSource;
import javax.activation.URLDataSource;
import javax.mail.Address;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.net.URL;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

public class DtsEmailUtils {

    public static final String MY_EMAIL_ACCOUNT = "dts@99bill.com";
    public static final String MY_EMAIL_PASSWORD = "1qaz@WSX";

    public static final String MY_SMTP_HOST = "sh-nlb-mhc.99bill.com";


    /***
     * describe: 发送email
     * creat_time: 2018/11/22 16:41
     * param: [params]
     * key:emailAddresses -->邮件列表 多人用 , 分隔开
     * key:subject --> 邮件主题
     * key:attachments -->邮件附件地址 多个地址用逗号隔开
     * key:attchCount  -->邮件附件个数
     * key:filename1   -->附件1的name
     * key:fielname2  -->附件2的name  与附件个数对应
     * key:htmlTemplate -->邮件模板html
     * key:htmlParamCount -->html模板里面动态传入参数的个数
     * key:htmlParam1 -->html模板里面动态传入参数第一个
     * key:htmlParam2 -->html模板里面动态传入参数第二个  可以传任意个数 只要与 htmlParamCount 对应即可
     *
     * return: java.lang.Integer
     */
    public static Integer sendEmail(Map<String, String> params) throws Exception {
        Integer responseCode = HttpStatus.SC_INTERNAL_SERVER_ERROR;
        try {
            // 1. 创建参数配置, 用于连接邮件服务器的参数配置
            Properties props = new Properties();                    // 参数配置
            props.setProperty("mail.transport.protocol", "smtp");   // 使用的协议（JavaMail规范要求）
            props.setProperty("mail.smtp.host", MY_SMTP_HOST);   // 发件人的邮箱的 SMTP 服务器地址
            props.setProperty("mail.smtp.auth", "true");            // 需要请求认证

            final String smtpPort = "25";
            props.setProperty("mail.smtp.port", smtpPort);

            // 2. 根据配置创建会话对象, 用于和邮件服务器交互
            Session session = Session.getInstance(props);
            // 设置为debug模式, 可以查看详细的发送 log
            session.setDebug(true);

            // 3. 创建一封邮件
            MimeMessage message = createMimeMessage(session, MY_EMAIL_ACCOUNT, params);

            // 4. 根据 Session 获取邮件传输对象
            Transport transport = session.getTransport();

            transport.connect(MY_EMAIL_ACCOUNT, MY_EMAIL_PASSWORD);

            // 6. 发送邮件, 发到所有的收件地址, message.getAllRecipients() 获取到的是在创建邮件对象时添加的所有收件人, 抄送人, 密送人
            transport.sendMessage(message, message.getAllRecipients());

            // 7. 关闭连接
            transport.close();
            responseCode = HttpStatus.SC_OK;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return responseCode;
    }

    /*** 
     * describe: 创建消息
     * creat_time: 2018/11/21 14:01
     * param: [session, sendMail, params]
     * return: javax.mail.internet.MimeMessage
     */
    public static MimeMessage createMimeMessage(Session session, String sendMail, Map<String, String> params) throws Exception {
        // 1. 创建一封邮件
        MimeMessage message = new MimeMessage(session);

        // 2. From: 发件人（昵称有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改昵称）
        message.setFrom(new InternetAddress(sendMail));

        // 3. To: 收件人（可以增加多个收件人、抄送、密送）
        String[] emailAddresses = params.get("emailAddresses").split(",");
        int addlength = emailAddresses.length;
        Address[] addresses = new Address[addlength];
        for (int i = 0; i < addlength; i++) {
            Address address = new InternetAddress(emailAddresses[i]);
            addresses[i] = address;
        }

        message.setRecipients(MimeMessage.RecipientType.TO, addresses);

        // 4. Subject: 邮件主题（标题有广告嫌疑，避免被邮件服务器误认为是滥发广告以至返回失败，请修改标题）
        if(params.containsKey("subject")){
            message.setSubject(params.get("subject"), "UTF-8");
        }else{
            message.setSubject("无主题", "UTF-8");
        }

        //整封邮件的MINE消息体
        MimeMultipart msgMultipart = new MimeMultipart("mixed");//混合的组合关系
        //设置邮件的MINE消息体
        message.setContent(msgMultipart);
        Integer attchCount=Integer.valueOf(params.get("attchCount"));
        String[] attachments = params.get("attachments").split(",");
        for(int i=0;i<attchCount;i++){
            //附件1
            MimeBodyPart attch = new MimeBodyPart();

            //把内容，附件1，附件2加入到 MINE消息体中
            msgMultipart.addBodyPart(attch);
            //把文件，添加到附件1中
            //数据源
            DataSource ds = new URLDataSource(new URL(attachments[i]));
            //数据处理器
            DataHandler dh = new DataHandler(ds);
            //设置第一个附件的数据
            attch.setDataHandler(dh);
            //设置第一个附件的文件名
            attch.setFileName(params.get("filename"+(i+1)));
        }
        //正文内容
        MimeBodyPart content = new MimeBodyPart();
        msgMultipart.addBodyPart(content);

        //正文（图片和文字部分）
        MimeMultipart bodyMultipart = new MimeMultipart("related");
        //设置内容为正文
        content.setContent(bodyMultipart);

        //html代码部分
        MimeBodyPart htmlPart = new MimeBodyPart();


        //正文添加图片和html代码
        bodyMultipart.addBodyPart(htmlPart);

        //把文件，添加到图片中
        String htmlTemplate = params.get("htmlTemplate");
        Integer htmlParamCount = Integer.valueOf(params.get("htmlParamCount"));

        for(int i=1;i<=htmlParamCount;i++){
            String htmlParami="htmlParam"+i;
            htmlTemplate = htmlTemplate.replace("${" + htmlParami + "}", params.get(htmlParami));
        }


        htmlPart.setContent(htmlTemplate, "text/html;charset=UTF-8");

        // 6. 设置发件时间
        message.setSentDate(new Date());

        // 7. 保存设置
        message.saveChanges();

        return message;
    }

    public static void main(String[] args) throws Exception{
////***
//     * describe: 发送email
//                * creat_time: 2018/11/22 16:41
//                * param: [params]
//     * key:emailAddresses -->邮件列表 多人用 , 分隔开
//                * key:subject --> 邮件主题
//                * key:attachments -->邮件附件地址 多个地址用逗号隔开
//                * key:attchCount  -->邮件附件个数
//                * key:filename1   -->附件1的name
//                * key:fielname2  -->附件2的name  与附件个数对应
//                * key:htmlTemplate -->邮件模板html
//                * key:htmlParamCount -->html模板里面动态传入参数的个数
//                * key:htmlParam1 -->html模板里面动态传入参数第一个
//                * key:htmlParam2 -->html模板里面动态传入参数第二个  可以传任意个数 只要与 htmlParamCount 对应即可
        Map<String,String> params=new HashMap<>();
        params.put("subject","test测试邮件");
        params.put("attachments","http://192.168.15.164:8888/tableauViewPic/SJPT20181118/dashboard.png,http://192.168.15.164:8888/tableauViewPic/SJPT20181118/taskOverview.png,http://192.168.15.164:8888/tableauViewPic/SJPT20181118/runnionContainersOversize.png");
        params.put("attchCount","3");
        params.put("filename1","filename1.png");
        params.put("filename2","filename2.png");
        params.put("filename3","filename3.png");
        params.put("htmlTemplate","<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Transitional//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd\">\n" +
                "<html xmlns=\"http://www.w3.org/1999/xhtml\">\n" +
                "<head><meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\" />\n" +
                "</head>\n" +
                "<body>\n" +
                "<table cellSpacing=\"0\" cellPadding=\"10\" width=\"800\" border=\"0\">\n" +
                "  <tbody>\n" +
                "  <tr>\n" +
                "    <td bgcolor=\"#FFFFFF\">\n" +
                "   <table width=\"500\" border=\"0\" cellpadding=\"10\" cellspacing=\"0\">\n" +
                "     <tr>\n" +
                "        <td>\n" +
                "      <br>\n" +
                "      Hi All：</span>\n" +
                "      <br>\n" +
                "       这里是您的${htmlParam1}订阅${htmlParam2}(详情${htmlParam3}见附件),数据由DTS提供计算服务,如有疑问请联系li.fang@99bill.com</span>\n" +
                "      <br>\n" +
                "      </td>\n" +
                "     </tr>\n" +
                "     <tr>\n" +
                "     <td>\n" +
                "      此为系统自动邮件，请勿回复。\n" +
                "      <br>\n" +
                "    多谢!\n" +
                "     </td>\n" +
                "     </tr>\n" +
                "</table></td></tr></tbody></table></body></html>");
        params.put("htmlParamCount","3");
        params.put("htmlParam1","--参数1--");
        params.put("htmlParam2","--参数2--");
        params.put("htmlParam3","--参数3--");
        params.put("emailAddresses","jun.li.wb@99bill.com,li.fang@99bill.com");

        DtsEmailUtils.sendEmail(params);


    }



}
